package com.hoperun.aop;

import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.hoperun.bean.base.BaseBean;
import com.hoperun.utils.LoginHelper;

@Aspect
public class EventAspect {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(EventAspect.class);

	@Before("save() || create() || register()")
	public void saveEvent(JoinPoint joinPoint) {
		// 取得方法名
		String methodName = joinPoint.getSignature().getName();

		Object[] args = joinPoint.getArgs();

		// TODO:目前只处理单个实体对象的更新和新增
		if (args == null || args.length != 1 || !(args[0] instanceof BaseBean)) {
			return;
		}

		// 取得审核参数
		BaseBean entity = (BaseBean) args[0];

		if (entity == null) {
			return;
		}

		// 取得Session
		Long id = LoginHelper.getLoginUserId();

		// 设置创建人
		entity.setCreator(id);

		// 设置创建时间
		entity.setCreatime(new Date());

		// 设置最终更新人
		entity.setUpdator(id);

		// 设置最后更新时间
		entity.setUpdatetime(new Date());

		LOGGER.debug(" save args is {}", JSONObject.toJSONString(args));
	}

	@Before("update()")
	public void updateEvent(JoinPoint joinPoint) {
		try {
			Object[] args = joinPoint.getArgs();
			LOGGER.debug("identity:update-user",
					"{'uid':'" + JSONObject.toJSONString(args) + "'}");
		} catch (Throwable e) {
			LOGGER.error(e.getMessage());
		}
	}

	@Before("delete()")
	public void deleteEvent(JoinPoint joinPoint) {
		try {
			Object[] args = joinPoint.getArgs();
			LOGGER.debug("delete", "{'uid':'" + JSONObject.toJSONString(args)
					+ "'}");
		} catch (Throwable e) {
			LOGGER.error(e.getMessage());
		}
	}

	@Pointcut("execution(* com.guo.an.market.service*..save*(..))")
	public void save() {
	}
	
	@Pointcut("execution(* com.guo.an.market.service*..create*(..))")
	public void create() {
	}

	@Pointcut("execution(* com.guo.an.markets.service*..update*(..))")
	public void update() {
	}

	@Pointcut("execution(* com.guo.an.markets.service*..delete*(..))")
	public void delete() {
	}
	
	@Pointcut("execution(* com.guo.an.markets.service*..register*(..))")
	public void register() {
	}
}
